package com.chenyun.common.utils;

import com.chenyun.common.context.ServletContext;
import com.chenyun.common.context.SpringContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

/**
 * @descriptions:
 * @author: Lonni
 * @date: 2021/1/4 20:55
 * @version: 1.0
 */
public class ThreadUtil {
    private static final Logger logger = LoggerFactory.getLogger(ThreadUtil.class);
    /**
     * 操作延迟10毫秒
     */
    private final int OPERATE_DELAY_TIME = 10;
    /**
     * 线程池
     */
    private ScheduledExecutorService scheduledExecutorService = SpringContext.getBean("scheduledExecutorService");
    /**
     * 定时调度线程池
     */
    private ThreadPoolTaskExecutor threadPoolTaskExecutor = SpringContext.getBean("threadPoolTaskExecutor");

    private ThreadUtil() {
    }

    private static ThreadUtil util = new ThreadUtil();

    public static ThreadUtil getInstance() {
        //设置request实例共享,传递给子线程
        ServletContext.setRequestToThreadShard();
        return util;
    }
    public ThreadPoolTaskExecutor getThreadPoolTaskExecutor() {
        return threadPoolTaskExecutor;
    }
    public ScheduledExecutorService getScheduledExecutorService() {
        return scheduledExecutorService;
    }
    public void  schedule(Runnable command){
        this.scheduledExecutorService.schedule(command,OPERATE_DELAY_TIME,TimeUnit.MILLISECONDS);
    }
    public void  schedule(Runnable command,
                          long delay, TimeUnit unit){
        this.scheduledExecutorService.schedule(command,delay,unit);
    }
    public  void execute(Runnable command){
        this.threadPoolTaskExecutor.execute(command);
    }
    public  <T> Future<T> execute(Callable<T> command){
      return  this.threadPoolTaskExecutor.submit(command);
    }



    /**
     * sleep等待,单位为毫秒
     */
    public static void sleep(long milliseconds) {
        try {
            Thread.sleep(milliseconds);
        } catch (InterruptedException e) {
            return;
        }
    }

    /**
     * 停止线程池
     * 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务.
     * 如果超时, 则调用shutdownNow, 取消在workQueue中Pending的任务,并中断所有阻塞函数.
     * 如果仍人超時，則強制退出.
     * 另对在shutdown时线程本身被调用中断做了处理.
     */
    public  void shutdownAndAwaitTermination( ExecutorService pool) {
        if (pool != null && !pool.isShutdown()) {
            pool.shutdown();
            try {
                if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
                    pool.shutdownNow();
                    if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
                        logger.info("Pool did not terminate");
                    }
                }
            } catch (InterruptedException ie) {
                pool.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }


    /**
     * 关闭线程池和调用池
     *
     */
    public void shutdownAndAwaitTermination(){
        this.shutdownAndAwaitTermination(scheduledExecutorService);
        /**
         * 此方法会先判断所有任务是否完成,完成直接调用shutdown
         * 如果没有,调用this.executor.shutdownNow()拿到通知结束的列表
         *   然后将当前执行的任务cancel调
         */
        this.threadPoolTaskExecutor.shutdown();
    }



    /**
     * 打印线程异常信息
     */
    public static void printException(Runnable r, Throwable t) {
        if (t == null && r instanceof Future<?>) {
            try {
                Future<?> future = (Future<?>) r;
                if (future.isDone()) {
                    future.get();
                }
            } catch (CancellationException ce) {
                t = ce;
            } catch (ExecutionException ee) {
                t = ee.getCause();
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
            }
        }
        if (t != null) {
            logger.error(t.getMessage(), t);
        }
    }

}
